package com.ydl.elasticsearch.controller;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ydl.elasticsearch.entity.CarEla;
import com.ydl.elasticsearch.repository.CarRepository;


@Controller
@RequestMapping(value="/car")
public class ApiCarController {
	
 	@Autowired
 	CarRepository carRepository;
	
	@ResponseBody
	@GetMapping(value="search")
	public List<CarEla> search(@RequestParam(value="key") String key) {
		BoolQueryBuilder builder = QueryBuilders.boolQuery();
		for (String str : getKeysName()) {
			builder.should(QueryBuilders.matchQuery(str, key));
		}
		// 当输入一个字的时候 也要搜索出相关内容
		for (String str : getKeysKeywordName()) {
			builder.should(QueryBuilders.wildcardQuery(str, "*"+ key +"*"));
		}
		NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
		queryBuilder.withQuery(builder);
		NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
		nativeSearchQueryBuilder.withQuery(builder);
		Page<CarEla> items = carRepository.search(queryBuilder.build());
		items.forEach(item -> System.out.println("item = " + item.getId()));
		return items.getContent();
	}
	
	
	private List<String> getKeysName() {
		List<String> keyName = new ArrayList<>();
		keyName.add("brand");
		keyName.add("colour");
		keyName.add("model");
		return keyName;
	}
	
	private List<String> getKeysKeywordName() {
		List<String> keyName = new ArrayList<>();
		keyName.add("brand.keyword");
		keyName.add("colour.keyword");
		keyName.add("model.keyword");
		return keyName;
	}
	
}
  
